package com.ruoyi.modules.monitor.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

/**
 * 监控权限配置
 *
 * @author ruoyi
 */
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    private static final Logger log = LoggerFactory.getLogger(WebSecurityConfigurer.class);

    private final String adminContextPath;

    private static String IP_List;

    @Value("${whitelist.ip}")
    private void setIp(String ip) {
        IP_List = ip;
        log.info("打印IP_List={}", IP_List);
    }

    public WebSecurityConfigurer(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");
        http
                .headers().frameOptions().disable()
                .and().authorizeRequests()
                //限制IP登陆
                .antMatchers(adminContextPath + "/assets/**"
                        , adminContextPath + "/login"
                        , adminContextPath + "/actuator/**"
                        , adminContextPath + "/instances/**"
                ).access(WebSecurityConfigurer.hasIpAddress())
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminContextPath + "/login")
                .successHandler(successHandler).and()
                .logout().logoutUrl(adminContextPath + "/logout")
                .and()
                .httpBasic().and()
                .csrf()
                .disable();
    }

    /**
     * 拼接白名单校验
     *
     * @return
     */
    public static String hasIpAddress() {
        StringBuilder str = new StringBuilder();
        if (ToolUtil.isNotEmpty(IP_List)) {
            String ipList = IP_List.trim().replace("，", ",");
            int i = 0;
            for (String ipAddress : ToolUtil.getSplit(ipList)) {
                if (i == 0) {
                    str.append("hasIpAddress('").append(ipAddress).append("') ");
                } else {
                    str.append("or hasIpAddress('").append(ipAddress).append("') ");
                }
                i++;
            }
        }
        log.info("打印白名单拼接语句 str.toString()={}", str.toString());
        return str.toString();
    }
}
